package com.jp.knowledge.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.dialog.LoadingDialog;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.LoginActivity;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.BaseActivity;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.HeadLineDailog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.HeadLine;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.PositionKnowlegeMode;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.activity.IntegralBuyActivity;
import com.jp.knowledge.my.activity.ToBeVipOrganize;
import com.jp.knowledge.my.activity.VipActivity;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.TabView;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.content.Intent.ACTION_DATE_CHANGED;

/**
 * Created by 528787067@qq.com on 2017/7/15.
 */

public class DailyKnowledgeFragment extends Fragment implements View.OnClickListener, ResultSubscriber.OnResultListener {

	private static final int GET_TAB_DATA = 0x01;
	private static final int PAY_CODE = 0x02;

	private View contentView;
	@ViewInject(R.id.module_name)
	private TextView titleView;
	@ViewInject(R.id.icon_left)
	private ImageView leftIcon;
	@ViewInject(R.id.icon_serach)
	private ImageView rightIcon;
	@ViewInject(R.id.tab_view)
	private TabView tabView;
	@ViewInject(R.id.view_pager)
	private ViewPager viewPager;
	@ViewInject(R.id.permissionLayout)
	private FrameLayout remindView;
	@ViewInject(R.id.remind_img)
	private ImageView remindImg;
	@ViewInject(R.id.remind_text)
	private TextView remindText;
	@ViewInject(R.id.remind_btn)
	private TextView remindBtn;

	private String[] weekDays;
	private DateFormat toastDateFormat;

	private DateFormat tabDateFormat;
	private Calendar startCalendar;
	private Calendar endCalendar;
	private Calendar selectedCalenar;
	private TimePickerView timePicker;
	private HeadLineDailog navDialog;

	private Context mContext;
	private String selectedNavType;
	private List<PositionKnowlegeMode> tabDatas;
	private List<HeadLine> headLines;
	private List<String> tabNames;
//	private List<DailyKnowledgeDetailFragment> dayFragments;
	private List<DailyKnowledgeDetailListFragment> dayFragments;
	private FragmentStatePagerAdapter pagerAdapter;

	private String cachePath;
	private FileCacheManager cacheManager;
	private SharedPreferences sharedPreferences;

	private CommDialog payDialog;
	private BroadcastReceiver broadcastReceiver;
	private LocalBroadcastManager localBroadcastManager;

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if(contentView == null){
			mContext = getContext();
			tabDatas = new ArrayList<>();
			headLines = new ArrayList<>();
			tabNames = new ArrayList<>();
			dayFragments = new ArrayList<>();
			toastDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
			tabDateFormat = new SimpleDateFormat("yy年MM月dd日", Locale.getDefault());
			weekDays = new String[]{"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
			startCalendar = Calendar.getInstance();
			startCalendar.set(2000, 0, 1);
			endCalendar = Calendar.getInstance();
			endCalendar.set(2099, 11, 31);
			cachePath = mContext.getCacheDir().getPath() + "/headLineDatas.dat";
			cacheManager = new FileCacheManager();
			sharedPreferences = mContext.getSharedPreferences("DailyKnowledge", Context.MODE_PRIVATE);
			selectedNavType = sharedPreferences.getString("selectedNavType", null);
			contentView = View.inflate(mContext, R.layout.fragment_knowledge, null);
			x.view().inject(this, contentView);
			initView();
			initDialog();
			initTimerPicker();
			initFragmentView();
			initBroadCast();
//			viewPager.setCurrentItem(dayFragments.size()-2, false);
			readCache();
		}
		return contentView;
	}

	@Override
	public void onDestroy() {
		mContext.unregisterReceiver(broadcastReceiver);
		localBroadcastManager.unregisterReceiver(broadcastReceiver);
		super.onDestroy();
	}

	private void initView(){
		rightIcon.setVisibility(View.GONE);
		leftIcon.setVisibility(View.VISIBLE);
		leftIcon.setImageResource(R.mipmap.calendar);
		leftIcon.setOnClickListener(this);
		titleView.setText("");
		titleView.setOnClickListener(this);
		titleView.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.mipmap.triangle), null);
		pagerAdapter = new FragmentStatePagerAdapter(getFragmentManager()) {
			@Override
			public Fragment getItem(int position) {
				return dayFragments.get(position);
			}
			@Override
			public int getCount() {
				return dayFragments.size();
			}
			@Override
			public int getItemPosition(Object object) {
				return POSITION_NONE;
			}
		};
		viewPager.setAdapter(pagerAdapter);
		tabView.setupWithViewPager(viewPager);
		remindBtn.setTag(0);
		remindBtn.setOnClickListener(this);
	}

	private void initDialog(){
		navDialog = new HeadLineDailog(mContext, headLines);
		navDialog.setCallback(new HeadLineDailog.HeadDialogCallback() {
			@Override
			public void done(HeadLine headLine, int position) {
				navSelected(position);
			}
		});
		payDialog = new CommDialog(mContext);
		payDialog.setRightListener(this);
	}

	private void initTimerPicker(){
		TimePickerView.OnTimeSelectListener timeSelectListener = new TimePickerView.OnTimeSelectListener() {
			@Override
			public void onTimeSelect(Date date, View v) {
				Date maxSupportDate = getMaxSupportCalendar().getTime();
				if(maxSupportDate.getTime() < date.getTime()){
					ToasUtil.toast(mContext, "最大可选日期：" + toastDateFormat.format(maxSupportDate));
				} else{
					selectedCalenar.setTime(date);
					initFragmentView();
					viewPager.setCurrentItem(0, false);
					timePicker.dismiss();
				}
			}
		};
		CustomListener customListener = new CustomListener() {
			@Override
			public void customLayout(View v) {
				TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
				TextView ivCancel = (TextView) v.findViewById(R.id.iv_cancel);
				tvSubmit.setOnClickListener(DailyKnowledgeFragment.this);
				ivCancel.setOnClickListener(DailyKnowledgeFragment.this);
			}
		};
		timePicker = new TimePickerView.Builder(mContext, timeSelectListener)
				.setType(new boolean[]{true, true, true, false, false, false})
				.setLayoutRes(R.layout.pickerview_custom_time, customListener)
				.setDividerColor(getResources().getColor(R.color.gray_deep))
				.setRangDate(startCalendar, endCalendar)
				.isCenterLabel(false)
				.isCyclic(true)
				.build();
	}

	private void initFragmentView(){
		int count = selectedCalenar == null ? 8 : 9;
		while(dayFragments.size() < count)
//			dayFragments.add(0, new DailyKnowledgeDetailFragment());
			dayFragments.add(0, new DailyKnowledgeDetailListFragment());
		while(tabNames.size() < count)
			tabNames.add(0, null);
		while (dayFragments.size() > count)
			dayFragments.remove(0);
		while(tabNames.size() > count)
			tabNames.remove(0);
		for(int i = 0; i < count; i++)
			dayFragments.get(i).updateData(selectedNavType);
//		for(int i = 0; i < 8; i++){
//			Calendar calendar = Calendar.getInstance();
//			calendar.add(Calendar.DATE, 1-i);
//			dayFragments.get(count-i-1).updateData(calendar);
//			tabNames.set(i, weekDays[calendar.get(Calendar.DAY_OF_WEEK) - 1]);
//		}
		for(int i = 0; i < 8; i++){
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.DATE, -i);
			dayFragments.get(count-8+i).updateData(calendar);
			tabNames.set(count-8+i, weekDays[calendar.get(Calendar.DAY_OF_WEEK) - 1]);
		}
		if(selectedCalenar != null){
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(selectedCalenar.getTime());
			dayFragments.get(0).updateData(calendar);
			tabNames.set(0, tabDateFormat.format(calendar.getTime()));
		}
//		tabNames.set(count-1, "明天");
//		tabNames.set(count-2, "今天");
//		tabNames.set(count-3, "昨天");
		tabNames.set(count-8, "今天");
		tabNames.set(count-8+1, "昨天");
		tabView.setTabItems(tabNames);
		pagerAdapter.notifyDataSetChanged();
	}


	private void initBroadCast(){
		localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
		broadcastReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if(ACTION_DATE_CHANGED.equals(action)) {
					initFragmentView();
				} else if(LocalBroadCast.LOGIN_SUCCESS_BROD.equals(action) && remindBtn.getVisibility() == View.VISIBLE){
					remindBtn.setVisibility(View.GONE);
				} else {
					if(LocalBroadCast.PAY_TO_READ.equals(action) && remindBtn.getVisibility() == View.VISIBLE)
						remindBtn.setVisibility(View.GONE);
					getData();
				}
			}
		};
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(LocalBroadCast.HEAD_LINE_SORT);
		intentFilter.addAction(LocalBroadCast.GET_LOGIN_INFO);
		intentFilter.addAction(LocalBroadCast.LOGOUT_SUCCESS_BROD);
		intentFilter.addAction(LocalBroadCast.LOGIN_SUCCESS_BROD);
		intentFilter.addAction(LocalBroadCast.USER_DATA_CHANGE);
		intentFilter.addAction(LocalBroadCast.PAY_TO_READ);
		localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
		mContext.registerReceiver(broadcastReceiver, new IntentFilter(ACTION_DATE_CHANGED));
	}

	private void navSelected(int position){
		selectedNavType = headLines.get(position).getTypeId();
//		for(DailyKnowledgeDetailFragment fragment : dayFragments)
		for(DailyKnowledgeDetailListFragment fragment : dayFragments)
			fragment.updateData(selectedNavType);
		for(int i = 0; i < headLines.size(); i++)
			headLines.get(i).setCheck(i == position);
		titleView.setText(headLines.get(position).getTypeName());
		navDialog.update(headLines);
		sharedPreferences.edit().putString("selectedNavType", selectedNavType).apply();
		setRemindView(tabDatas.get(position));
	}

	private void setRemindView(PositionKnowlegeMode data){
		remindView.setVisibility(View.VISIBLE);
		remindImg.setImageResource(R.mipmap.no_data_hint);
		if(data == null){
			remindText.setText("暂时没有数据~");
			remindBtn.setVisibility(View.GONE);
		} else if(data.getState() == 0){
			remindText.setText("内容因版权问题已被删除~");
			remindBtn.setVisibility(View.GONE);
		} else if(data.getState() == 2){
			remindImg.setImageResource(R.mipmap.message_prompt);
			remindText.setText("栏目即将开放，敬请等候~");
			remindBtn.setVisibility(View.GONE);
		} else {
			remindText.setText(data.getViewPrompt());
			remindBtn.setVisibility(View.VISIBLE);
			remindBtn.setTag(data.getViewPermit());
			switch (data.getViewPermit()){
				case -1:    // -1 需先登录
				case 6:     // 6 次数超过100
					remindBtn.setText("登陆");
					break;
				case 2:     // 2 用户可见
				case 3:     // 3 企业可见
				case 9:
					remindBtn.setVisibility(View.GONE);
					break;
				case 1:     // 1 用户VIP可见
					remindBtn.setText("我要升级");
					break;
				case 7:     // 7 次数超过1000
					remindBtn.setText("我要成为VIP企业");
					break;
				case 5:     // 5 企业VIP可见
					UserData userData = ((JpApplication)getActivity().getApplication()).getUserData();
					if(userData == null || userData.getCompanyList() == null || userData.getCompanyList().size() == 0){
						remindBtn.setVisibility(View.GONE);
						remindText.setText("你无权限阅读");
					} else{
						remindBtn.setText("我要成为VIP企业");
					}
					break;
				case 4:     // 4 付费（有两种付费方式）
					remindText.setText(String.format("需支付%d知识币才能查看", data.getIntegral()));
					remindBtn.setText("付费");
					break;
				case 0:     // 0 允许查看
				default:
					if(TextUtils.isEmpty(data.getNavType())){
						remindText.setText("暂时没有数据~");
						remindBtn.setVisibility(View.GONE);
					} else {
						remindView.setVisibility(View.GONE);
					}
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.icon_left:
				if (selectedCalenar == null){
					selectedCalenar = Calendar.getInstance();
					selectedCalenar.add(Calendar.DATE, -8);
				}
				timePicker.setDate(selectedCalenar);
				timePicker.show();
				break;
			case R.id.module_name:
				navDialog.showDialog();
				break;
			case R.id.tv_finish:
				timePicker.returnData();
				break;
			case R.id.iv_cancel:
				timePicker.dismiss();
				break;
			case R.id.remind_btn:
				int viewPermit = (int) v.getTag();
				if(viewPermit == -1){           // 登陆
					startActivity(new Intent(mContext, LoginActivity.class));
				} else if(viewPermit == 1){   // 升级 VIP
					startActivity(new Intent(mContext, VipActivity.class));
				} else if(viewPermit == 5){    // 成为 VIP 企业
					startActivity(new Intent(mContext, ToBeVipOrganize.class));
				} else if(viewPermit == 4){		// 付费
					UserData userData = ((JpApplication) getActivity().getApplication()).getUserData();
					if (userData == null || userData.getIsLogin() != 1) {
						startActivity(new Intent(mContext, LoginActivity.class));
						return;
					}
					PositionKnowlegeMode data = tabDatas.get(getSelectIndex());
					if (userData.getIntegralNum() >= data.getIntegral()) {
						payDialog.setTag(true);
						payDialog.setContent("是否确定支付" + data.getIntegral() + "知识币下载内容？");
					} else {
						payDialog.setTag(false);
						payDialog.setContent("你当前知识币不足，是否充值知识币？");
					}
					payDialog.show();
				}
				break;
			case R.id.right_btn:
				if((boolean)payDialog.getTag()){
					PositionKnowlegeMode data = tabDatas.get(getSelectIndex());
					JsonObject param = new JsonObject();
					param.addProperty("type", 0);
					param.addProperty("id", data.getId());
					param.addProperty("integral", data.getIntegral());
					HttpHelper.getInstance(mContext).integralPurchase(param, PAY_CODE, this);
				} else{
					startActivity(new Intent(mContext, IntegralBuyActivity.class));
				}
				break;
		}
	}

	private int getSelectIndex(){
		int selectedPosition = 0;
		for(int i = 0; i < headLines.size(); i++) {
			if (headLines.get(i).getTypeId().equals(selectedNavType)){
				selectedPosition = i;
				break;
			}
		}
		return selectedPosition;
	}

	private void getData(){
		JsonObject param = new JsonObject();
		param.addProperty("token", HttpHelper.token);
		param.addProperty("type", 12);
//		HttpHelper.getInstance(mContext).getHeadLine(param, GET_TAB_DATA, this);
		HttpHelper.getInstance(mContext).getSkill(new JsonObject(), GET_TAB_DATA, this);
	}

	@Override
	public void onStart(int requestType) {
		if(requestType == PAY_CODE)
			((BaseActivity)getActivity()).showLoading();
	}

	@Override
	public void onCompleted(int requestType) {
		if(requestType == PAY_CODE)
			((BaseActivity)getActivity()).cancleLoading();
	}

	@Override
	public void onError(int requestType) {
		onCompleted(requestType);
		if(requestType == GET_TAB_DATA) {
			contentView.postDelayed(new Runnable() {
				@Override
				public void run() {
					getData();
				}
			}, 1000);
		}
	}

	@Override
	public void onNext(IModel data, int requestType) {
		if(data.getErrcode() != 0){
//			ToasUtil.toast(mContext, data.getMessage());
		} else if(requestType == GET_TAB_DATA){
//			headLines.clear();
//			List<HeadLine> tmpDatas = data.getList(HeadLine.class);
//			if(tmpDatas != null && tmpDatas.size() > 0)
//				headLines.addAll(tmpDatas);
//			int selectedPosition = 0;
//			for(int i = 0; i < headLines.size(); i++) {
//				if (headLines.get(i).getTypeId().equals(selectedNavType)){
//					selectedPosition = i;
//					break;
//				}
//			}
//			navSelected(selectedPosition);
//			writeCache(cachePath, headLines);

			List<PositionKnowlegeMode> datas = data.getList(PositionKnowlegeMode.class);
			setData(datas);
			writeCache(cachePath, datas);
		} else if(requestType == PAY_CODE){
			localBroadcastManager.sendBroadcast(new Intent(LocalBroadCast.PAY_TO_READ));
		}
	}

	private void setData(List<PositionKnowlegeMode> datas){
		tabDatas.clear();
		headLines.clear();
		if(datas != null) {
			tabDatas.addAll(datas);
			for (PositionKnowlegeMode model : datas) {
				HeadLine headLine = new HeadLine();
				headLine.setTypeName(model.getName());
				headLine.setTypeId(model.getNavType());
				headLines.add(headLine);
			}
		}
		navSelected(getSelectIndex());
	}

	private void readCache(){
		Observable.create(new Observable.OnSubscribe<List<PositionKnowlegeMode>>() {
			@Override
			public void call(Subscriber<? super List<PositionKnowlegeMode>> subscriber) {
				List<PositionKnowlegeMode> datas = (List) cacheManager.readObject(cachePath);
				subscriber.onNext(datas);
				subscriber.onCompleted();
			}
		}).subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribe(new Subscriber<List<PositionKnowlegeMode>>() {
			@Override
			public void onCompleted() {
				getData();
			}
			@Override
			public void onError(Throwable e) {
				onCompleted();
			}
			@Override
			public void onNext(List<PositionKnowlegeMode> data) {
				setData(data);
			}
		});
	}

	private void writeCache(final String cachePath, final Object data){
		new Thread(new Runnable() {
			@Override
			public void run() {
				cacheManager.wirteObject(data, cachePath);
			}
		}).start();
	}

	private Calendar getMaxSupportCalendar(){
		Calendar maxSupportCalendar = Calendar.getInstance();
//		maxSupportCalendar.add(Calendar.DATE, -7);
		UserData userData = ((JpApplication)getActivity().getApplication()).getUserData();
		if(userData != null && userData.getPlatformAdmin() == 1)
			maxSupportCalendar = (Calendar) endCalendar.clone();
		else
			maxSupportCalendar.add(Calendar.DATE, -8);
		return maxSupportCalendar;
	}
}
